package com.gao.i_retry;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author gao
 * @time 2022/07/07 15:15:48
 */
@Component
@Slf4j
public class Consumer {
    private int retryTimes = 0;

    @RabbitListener(
            bindings = {
                    @QueueBinding(
                            value = @Queue(name = "queue_test"),
                            exchange = @Exchange(value = "exchange_demo", type = ExchangeTypes.DIRECT),
                            key = "rk"
                    )
            }

    )
    public void receive(Message message, Channel channel) throws IOException {
        try {
            String msg = new String(message.getBody());
            log.info("第{}次接收到消息，接受到消息：{}", ++retryTimes, msg);
            int i = 8 / 0;
            log.info("消费完消息：{}", msg);
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            System.out.println(e);
            // 手动确认消息
            if (retryTimes >= 5) {
                retryTimes = 0;
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
            throw new RuntimeException(e);
        }
    }
}
